package edu.gatech.wms.views;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import edu.gatech.wms.R;
import edu.gatech.wms.controllers.Login;

//import edu.gatech.wms.views.LoginActivity.UserLoginTask;

public class LoginActivity extends Activity
{
	/**
	 * Keep track of the login task to ensure we can cancel it if requested.
	 */
	// private UserLoginTask mAuthTask = null;
	private Login				login;
	private static final int	REGISTER	= 1;

	// Values for email and password at the time of the login attempt.
	private String				mEmail;
	private String				mPassword;

	// UI references.
	private EditText			mEmailView;
	private EditText			mPasswordView;
	private boolean				isAdmin;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loginactivity);
		login = Login.getLoginObject();

		// Set up the login form.
		mEmailView = (EditText) findViewById(R.id.email);
		mEmailView.setSaveEnabled(false);
		mPasswordView = (EditText) findViewById(R.id.password);
		mPasswordView.setSaveEnabled(false);
		mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener()
		{
			@Override
			public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent)
			{
				if (id == R.id.login || id == EditorInfo.IME_NULL)
				{
					attemptLogin();
					return true;
				}
				return false;
			}
		});

		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(mPasswordView.getWindowToken(), 0);
		imm.hideSoftInputFromWindow(mEmailView.getWindowToken(), 0);

		findViewById(R.id.sign_in_button).setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View view)
			{
				if(attemptLogin())
				{
					Intent intent = new Intent(getBaseContext(), MainActivity.class);
					intent.putExtra(Login.IS_ADMIN, isAdmin);
					startActivity(intent);
				}
			}
		});

		findViewById(R.id.register_button).setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View view)
			{
				Intent i = new Intent(getBaseContext(), RegisterActivity.class);
				startActivityForResult(i, REGISTER);
			}
		});
	}

	/**
	 * Attempts to sign in or register the account specified by the login form.
	 * If there are form errors (invalid email, missing fields, etc.), the
	 * errors are presented and no actual login attempt is made.
	 */
	public boolean attemptLogin()
	{
		/*
		 * if (mAuthTask != null) { return; }
		 */

		// Reset errors.
		mEmailView.setError(null);
		mPasswordView.setError(null);

		// Store values at the time of the login attempt.
		mEmail = mEmailView.getText().toString();
		mPassword = mPasswordView.getText().toString();

		boolean cancel = false;
		View focusView = null;

		// Check for a valid password.
		if (TextUtils.isEmpty(mPassword))
		{
			mPasswordView.setError(getString(R.string.error_field_required));
			focusView = mPasswordView;
			cancel = true;
		}
		else if (mPassword.length() < 8)
		{
			mPasswordView.setError(getString(R.string.error_invalid_password));
			focusView = mPasswordView;
			cancel = true;
		}

		// Check for a valid email address.
		if (TextUtils.isEmpty(mEmail))
		{
			mEmailView.setError(getString(R.string.error_field_required));
			focusView = mEmailView;
			cancel = true;
		}
		else if (!mEmail.contains("@"))
		{
			mEmailView.setError(getString(R.string.error_invalid_email));
			focusView = mEmailView;
			cancel = true;
		}

		if (cancel)
		{
			// There was an error; don't attempt login and focus the first
			// form field with an error.
			focusView.requestFocus();
		}
		else
		{
			int login_val = login.authUser(mEmail, mPassword);
			if (login_val == Login.LOGIN_SUCCESS)
			{
				SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
				SharedPreferences.Editor editor = preferences.edit();
				editor.putInt(Login.ACTIVE_KEY, Login.getActiveKey());
				editor.commit();
				isAdmin = login.getIsAdmin();
				return true;
			}
			else if (login_val == Login.LOGIN_FAIL)
			{
				Toast.makeText(getBaseContext(), "Username/Password is wrong, please try again.",
						Toast.LENGTH_SHORT).show();
			}
			else if (login_val == Login.LOGIN_LOCKED)
			{
				Toast.makeText(getBaseContext(), "Your account is locked, please contact an admin.",
						Toast.LENGTH_SHORT).show();
			}
		}
		
		return false;
	}
	
	@Override
	public void onBackPressed() 
	{	
	}
}